#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSplitter>
#include <QMenuBar>
#include <QMenu>
#include <QAction>
#include <QStatusBar>
#include <QScreen>
#include <QApplication>
#include <QIcon>
#include <QKeySequence>
#include <QFileDialog>
#include <QMessageBox>
#include <QPushButton>
#include <QDesktopServices>
#include <QFileInfo>
#include <QDate>
#include <QDir>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 设置窗口标题和大小
    setWindowTitle("宿舍评分管理系统");
    resize(1024, 768);

    // 初始化数据库
    initializeDatabase();

    // 设置界面
    setupUi();

    // 添加菜单栏操作
    QMenu *fileMenu = menuBar()->addMenu("文件");

    // 添加数据备份与恢复子菜单
    QMenu *dbBackupMenu = fileMenu->addMenu("数据备份与恢复");
    dbBackupMenu->setIcon(QIcon::fromTheme("drive-harddisk"));

    QAction *exportAction = new QAction("导出数据库文件", this);
    exportAction->setIcon(QIcon::fromTheme("document-save"));
    exportAction->setShortcut(QKeySequence("Ctrl+E"));
    exportAction->setStatusTip("将当前数据库导出为SQLite文件以便备份");
    connect(exportAction, &QAction::triggered, this, &MainWindow::exportDatabase);
    dbBackupMenu->addAction(exportAction);

    QAction *importAction = new QAction("导入数据库文件", this);
    importAction->setIcon(QIcon::fromTheme("document-open"));
    importAction->setShortcut(QKeySequence("Ctrl+I"));
    importAction->setStatusTip("从SQLite文件导入数据库以恢复数据");
    connect(importAction, &QAction::triggered, this, &MainWindow::importDatabase);
    dbBackupMenu->addAction(importAction);

    // 添加分隔线
    fileMenu->addSeparator();

    // 添加退出操作
    QAction *exitAction = new QAction("退出", this);
    exitAction->setShortcut(QKeySequence("Ctrl+Q"));
    connect(exitAction, &QAction::triggered, this, &QWidget::close);
    fileMenu->addAction(exitAction);

    // 状态栏显示
    statusBar()->showMessage("准备就绪");

    // 确保窗口在屏幕中央显示
    if (QApplication::screens().size() > 0)
    {
        QScreen *screen = QApplication::primaryScreen();
        QRect screenGeometry = screen->geometry();
        int x = (screenGeometry.width() - width()) / 2;
        int y = (screenGeometry.height() - height()) / 2;
        move(x, y);
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::setupUi()
{
    // 创建主分割器
    QSplitter *mainSplitter = new QSplitter(Qt::Horizontal, this);
    setCentralWidget(mainSplitter);

    // 创建左侧菜单区域
    QWidget *leftPanel = new QWidget(mainSplitter);
    QVBoxLayout *leftLayout = new QVBoxLayout(leftPanel);
    leftPanel->setLayout(leftLayout);

    QLabel *menuTitle = new QLabel("系统菜单", leftPanel);
    menuTitle->setAlignment(Qt::AlignCenter);
    QFont titleFont = menuTitle->font();
    titleFont.setBold(true);
    titleFont.setPointSize(14);
    menuTitle->setFont(titleFont);

    menuList = new QListWidget(leftPanel);
    menuList->addItem("录入评分");
    menuList->addItem("按天查询");
    menuList->addItem("月度查询");
    menuList->addItem("宿舍管理");

    menuList->setCurrentRow(0);
    menuList->setFixedWidth(180);

    // 菜单项样式
    menuList->setStyleSheet(
        "QListWidget {"
        "   border: 1px solid #dcdcdc;"
        "   border-radius: 5px;"
        "   background-color: #f5f5f5;"
        "}"
        "QListWidget::item {"
        "   padding: 10px;"
        "   border-bottom: 1px solid #dcdcdc;"
        "}"
        "QListWidget::item:selected {"
        "   background-color: #007bff;"
        "   color: white;"
        "}");

    leftLayout->addWidget(menuTitle);
    leftLayout->addWidget(menuList);

    // 右侧内容区域
    contentStack = new QStackedWidget(mainSplitter);

    // 创建各个功能页面
    scoreEntryPage = new ScoreEntry(this);
    scoreQueryByDatePage = new ScoreQueryByDate(this);
    monthlyQueryPage = new MonthlyQuery(this);
    dormitoryManagePage = new DormitoryManage(this);

    // 添加页面到堆栈
    contentStack->addWidget(scoreEntryPage);
    contentStack->addWidget(scoreQueryByDatePage);
    contentStack->addWidget(monthlyQueryPage);
    contentStack->addWidget(dormitoryManagePage);

    // 设置默认页面
    contentStack->setCurrentIndex(0);

    // 连接菜单项点击信号
    connect(menuList, &QListWidget::currentRowChanged, this, &MainWindow::onMenuItemClicked);

    // 设置分割器的初始大小
    mainSplitter->setSizes(QList<int>() << 200 << 800);
    mainSplitter->setStretchFactor(0, 0);
    mainSplitter->setStretchFactor(1, 1);
}

void MainWindow::initializeDatabase()
{
    if (!database.openDatabase())
    {
        QMessageBox::critical(this, "错误", "无法打开数据库！");
        return;
    }

    if (!database.initializeDatabase())
    {
        QMessageBox::critical(this, "错误", "初始化数据库失败！");
        return;
    }

    // 初始化宿舍数据
    database.initializeDormitoryData();
}

void MainWindow::onMenuItemClicked(int index)
{
    contentStack->setCurrentIndex(index);

    // 更新状态栏
    QString statusMessage;
    switch (index)
    {
    case 0:
        statusMessage = "录入评分";
        break;
    case 1:
        statusMessage = "按天查询";
        break;
    case 2:
        statusMessage = "月度查询";
        break;
    case 3:
        statusMessage = "宿舍管理";
        break;
    }

    statusBar()->showMessage(statusMessage);
}

void MainWindow::exportDatabase()
{
    // 默认使用当前日期作为文件名建议
    QString defaultFileName = "宿舍评分系统数据库_" + QDate::currentDate().toString("yyyy-MM-dd") + ".db";
    QString defaultPath = QDir::homePath() + "/" + defaultFileName;

    QString filePath = QFileDialog::getSaveFileName(this, "导出数据库",
                                                    defaultPath,
                                                    "SQLite数据库文件 (*.db);;所有文件 (*)");
    if (filePath.isEmpty())
    {
        return;
    }

    // 显示进度指示
    statusBar()->showMessage("正在导出数据库...");
    QApplication::setOverrideCursor(Qt::WaitCursor);

    // 执行导出操作
    bool success = database.exportDatabase(filePath);

    // 恢复光标和状态栏
    QApplication::restoreOverrideCursor();
    statusBar()->showMessage("准备就绪", 3000);

    if (success)
    {
        QMessageBox msgBox(this);
        msgBox.setWindowTitle("导出成功");
        msgBox.setIcon(QMessageBox::Information);
        msgBox.setText("数据库已成功导出！");
        msgBox.setInformativeText("文件保存在: " + QDir::toNativeSeparators(filePath));

        QPushButton *openFolderButton = msgBox.addButton("打开所在文件夹", QMessageBox::ActionRole);
        QPushButton *okButton = msgBox.addButton("确定", QMessageBox::AcceptRole);
        msgBox.setDefaultButton(okButton);

        msgBox.exec();

        if (msgBox.clickedButton() == openFolderButton)
        {
            // 打开包含导出文件的文件夹
            QFileInfo fileInfo(filePath);
            QString folderPath = fileInfo.absolutePath();
            QDesktopServices::openUrl(QUrl::fromLocalFile(folderPath));
        }
    }
    else
    {
        QMessageBox::critical(this, "导出失败",
                              "数据库导出失败！\n请确保您有权限写入选择的位置，并且没有其他程序正在使用该文件。");
    }
}

void MainWindow::importDatabase()
{
    QString filePath = QFileDialog::getOpenFileName(this, "导入数据库",
                                                    QDir::homePath(),
                                                    "SQLite数据库文件 (*.db);;所有文件 (*)");
    if (filePath.isEmpty())
    {
        return;
    }

    // 询问用户是否了解导入风险
    QMessageBox confirmBox(this);
    confirmBox.setWindowTitle("导入确认");
    confirmBox.setIcon(QMessageBox::Warning);
    confirmBox.setText("您即将导入一个数据库文件。");
    confirmBox.setInformativeText("这将覆盖当前的所有数据，此操作无法撤销。确定要继续吗？");
    confirmBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    confirmBox.setDefaultButton(QMessageBox::No);

    if (confirmBox.exec() != QMessageBox::Yes)
    {
        return;
    }

    // 显示进度指示
    statusBar()->showMessage("正在导入数据库...");
    QApplication::setOverrideCursor(Qt::WaitCursor);

    // 执行导入操作
    bool success = database.importDatabase(filePath);

    // 恢复光标和状态栏
    QApplication::restoreOverrideCursor();
    statusBar()->showMessage("准备就绪", 3000);

    if (success)
    {
        QMessageBox::information(this, "导入成功",
                                 "数据库已成功导入！\n程序将刷新所有数据。");

        // 刷新所有页面
        scoreEntryPage->refreshData();
        scoreQueryByDatePage->refreshData();
        monthlyQueryPage->refreshData();
        dormitoryManagePage->refreshData();
    }
    else
    {
        QMessageBox::critical(this, "导入失败",
                              "数据库导入失败！\n可能的原因：\n- 选择的文件不是有效的SQLite数据库\n- 数据库格式不兼容\n- 数据库文件已损坏\n\n当前数据已恢复到导入前的状态。");
    }
}
